'use strict';

const Service = require('egg').Service;
const fs = require("fs");
const path = require("path");
function removeImg(name){
    let p = path.join(__dirname,`../public/upload/${name}`);
    try{
        fs.unlink(p,function(er){
            if(er){
                console.log("删除文件失败",p);
            }
        });
    }catch(e){
        console.log("删除失败",p)
    }
}

async function clearNoteImg(self,id){
    let res = await self.ctx.model.Note.findOne({"_id":id});
    if(res && res.type == self.app.const.noteType.img){
        removeImg(res.content);
    }
}


class NoteService extends Service {
    async add(opt){
        const {ctx,app} = this;
        let tag
        if(opt.tagId){
             tag = await ctx.model.Tag.findOne({"_id":opt.tagId});
             if(!tag){
                return Promise.reject(app.resCode.tagId)
            }
            opt.tagName = tag.name;
        }else{
            opt.tagName = "全部";
        }
        
        var config = new ctx.model.Note(opt);
        return config.save();  
    }
    async remove(id){
        // 如果删除的是画图类型的，则需要删除图片
        await clearNoteImg(this,id);
        return this.ctx.model.Note.deleteOne({"_id":id});
    }
    async update(id,opt){
        if(opt.tagId){
            // 需要修改 tagId
            let tag = await this.ctx.model.Tag.findOne({"_id":opt.tagId});
            opt.tagName = tag.name;
        }else{
            opt.tagName = "全部";
        }
        await clearNoteImg(this,id);
        return this.ctx.model.Note.updateOne({"_id":id},{"$set":opt});
    }
    async list(opt,uid){
        let pageSize = parseInt(opt.pageSize) || 20; //每页多少条
        let pageNum = parseInt(opt.pageNum) || 1; //多少页
        let skip = (pageNum - 1) * pageSize;
        let orderby = opt.orderby;
        if(orderby !== "title"){
            orderby = "updatedAt";
        }

        delete opt.pageSize;
        delete opt.pageNum;
        delete opt.orderby;
        
        let or = [];
        for(let i in opt){
            if(opt[i]){
                or.push({
                    [i]:opt[i]
                })
            }
        }
        let search = {uid};
        if(or.length > 0){
            search["$or"] = or;
        }
        let sort = {};
        sort[orderby] = -1;

        let list = await this.ctx.model.Note.find(search).sort(sort).skip(skip).limit(pageSize);
        let count = await this.ctx.model.Note.find(search).countDocuments();
        return Promise.resolve({list,count,pageSize,pageNum});
    }
    async info(id){
        return this.ctx.model.Note.findOne({"_id":id});
    }
    async groupByTags(uid){
        let notes = await this.ctx.model.Note.aggregate([
            {$match: {
                uid
            }},
            {$group: {_id: "$tagId", tagName:{$first:"$tagName"}, count: {$sum: 1}}}
         ]);
        let tags = await this.ctx.model.Tag.find({uid});
        //tags = tags.toObject();
        tags = JSON.parse(JSON.stringify(tags));
        let cache = {};
        for(let i = 0; i  < notes.length; i++){
            cache[notes[i]._id] = notes[i];
        }
        for(let j = 0; j < tags.length; j++){
            if(cache[tags[j]._id]){
                tags[j].count = cache[tags[j]._id].count;
            }else{
                tags[j].count =  0;
            }
        }
        return Promise.resolve(tags);
    }
}

module.exports = NoteService;